<!--
 * @Author: wei_jt@ecidi.com
 * @Date: 2019-11-07 09:36:16
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-04-14 11:08:02
 * @Description: 角色授权页
 -->
<template>
  <fks-dialog
    :visible.sync="show"
    :append-to-body="true"
    width="1000px"
    :title="LANG.MEMBER"
    class="dialog-8vh"
    top="8vh"
    @open="fetchData"
    @close="close"
  >
    <div slot="title"><i class="fks-icon-user" />{{ LANG.MEMBER }}</div>
    <div class="authorize">
      <fks-query-page
        ref="peopleTable"
        v-loading="listLoading"
        :data="list"
        :table-name="LANG.MEMBER"
        :current-page.sync="currentPage"
        :page-size.sync="pageSize"
        :total="total"
        @row-click="rowClick"
        @query="fetchData"
        @sort-change="sortHandler"
        @selection-change="handleSelect"
      >
        <template slot="singleSearch">
          <div class="single-searchBox">
            <fks-select v-model="memberType">
              <fks-option
                v-for="item in memberTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </fks-select>
            <fks-input
              v-model="selectName"
              style="margin-left: 10px"
              size
              class="single-searchBox-item"
              :placeholder="
                memberType == 'user'
                  ? LANG.MEMBER_SEARCH_PLACEHOLDER
                  : LANG.SEARCH_PLACEHOLDER
              "
              maxlength="50"
              clearable
              @clear="search"
              @keyup.enter.native="search"
            >
              <fks-button
                slot="append"
                icon="fks-icon-search"
                @click="search"
              />
            </fks-input>

            <fks-user-selector
              v-show="memberType == 'user'"
              :key="userNumber"
              :recentUser="false"
              multiple
              url
              width="auto"
              layout="branch"
              @change="addMembers"
            >
              <fks-button slot="reference" icon="fks-icon-plus">
                {{ LANG.ADD }}
              </fks-button>
            </fks-user-selector>
            <fks-button
              v-show="memberType != 'user'"
              icon="fks-icon-plus"
              @click="showMemberDialog = !showMemberDialog"
            >
              {{ LANG.ADD }}
            </fks-button>

            <fks-button
              style="margin-left: 10px"
              icon="fks-icon-delete"
              :disabled="delList.length < 1"
              @click="handleDelete"
            >
              {{ LANG.DELETE }}
            </fks-button>
          </div>
        </template>
        <template>
          <fks-table-column width="55" type="selection" />
          <template v-if="memberType == 'user'">
            <fks-table-column
              align="center"
              :label="LANG.USER_FULL_NAME"
              prop="userFullname"
              sortable="custom"
              min-width="120"
            />
            <fks-table-column
              :label="LANG.USERNAME"
              min-width="120"
              prop="userName"
              align="left"
              sortable="custom"
            />
          </template>
          <template v-else>
            <fks-table-column
              align="left"
              :label="LANG.NAME"
              prop="name"
              sortable="custom"
              min-width="120"
            />

            <fks-table-column
              :label="LANG.CODE"
              min-width="120"
              prop="code"
              align="left"
              sortable="custom"
            />
          </template>
          <!-- <fks-table-column
            align="center"
            prop="orgPathName"
            :label="LANG.DEPARTMENT"
            min-width="150"
          >
            <template slot-scope="scope">
              <span>{{
                scope.row.orgPathName
                  ? scope.row.orgPathName.replace(/^.|.$/g, '')
                  : ''
              }}</span>
            </template>
          </fks-table-column> -->
          <!-- <fks-table-column align="left" header-align="center" :label="LANG.OPERATION" min-width="150">
            <template slot-scope="scope">
              <fks-button
                @click="handleDelete(scope.$index, scope.row)"
                type="text"
                :disabled="role.roleCode === 'superManager'"
              ></fks-button>
            </template>
          </fks-table-column>-->
        </template>
      </fks-query-page>
    </div>
    <AddUserGroup
      v-if="showMemberDialog"
      :visible.sync="showMemberDialog"
      :group-type="memberType"
      @change="addMembers"
    />
  </fks-dialog>
</template>

<script type="text/ecmascript-6">
import * as Auth from '../api'
import * as User from '@/api/user'
import AddUserGroup from '../component/AddUserGroup'

export default {
  components: { AddUserGroup },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'success',
        '-1': 'danger'
      }
      return statusMap[status]
    },
    stateFilter(state) {
      const stateMap = {
        0: '激活',
        '-1': '停用'
      }
      return stateMap[state]
    }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      required: true
    }
  },
  data() {
    return {
      list: [],
      listLoading: false,
      currentPage: 1,
      pageSize: 20,
      total: 0,
      name: '',
      selectName: '',
      delList: [],
      role: {
        roleName: ''
      },
      show: this.visible,
      showMemberDialog: false,
      userNumber: 1,
      sort: '',
      columnName: '',
      memberType: 'user',

      methodList: {
        user: {
          get: Auth.getRoleUser,
          delete: Auth.deleteRoleUser,
          save: Auth.saveRoleUser
        },
        userGroup: {
          get: Auth.getRoleUserGroup,
          delete: Auth.deleteRoleUserGroup,
          save: Auth.saveRoleUserGroup
        }
      }
    }
  },
  computed: {
    portalId() {
      return this.$store.state.portal.id
    },
    multiPortal() {
      return this.$store.getters.multiPortal
    },
    currentMethod() {
      return this.methodList[this.memberType == 'user' ? 'user' : 'userGroup']
    },
    memberTypeList() {
      return [
        { value: 'user', label: this.LANG.USER, code: '' },
        { value: 'org', label: this.LANG.ORGANIZATION, code: 2 },
        { value: 'post', label: this.LANG.POST, code: 1 }
      ]
    },

    typeCode() {
      let type = this.memberTypeList.find(
        (item) => item.value == this.memberType
      )
      return type.code || ''
    }
  },
  watch: {
    visible() {
      this.show = this.visible
    },
    memberType() {
      //init式获取数据
      this.initData()
      this.fetchData()
    }
  },
  mounted() {},
  methods: {
    close() {
      this.selectName = ''
      this.show = false
      this.$emit('update:visible', this.show)
    },

    rowClick(row) {
      this.$refs.peopleTable.$refs.table.toggleRowSelection(
        row,
        this.changeSelected(row)
      )
    },
    changeSelected(row) {
      let w = true
      this.delList.forEach((item) => {
        if (item == row.id) {
          w = false
        }
      })
      return w
    },
    handleSelect(val) {
      this.delList = val.map((item) => {
        return item.id
      })
    },

    sortHandler(data) {
      if (!data.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
        this.columnName = data.prop
      }
      this.fetchData()
    },

    initData() {
      this.currentPage = 1
      this.pageSize = 20
      this.selectName = ''
      this.sort = ''
      this.columnName = ''
    },

    search() {
      this.currentPage = 1
      this.fetchData()
    },
    fetchData() {
      if (!this.data.id) {
        return false
      }
      this.listLoading = true

      const form = {
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        searchValue: this.selectName,
        roleId: this.data.id,
        type: this.typeCode,
        sort: this.sort,
        columnName: this.columnName
      }
      this.getDataList(form)
    },
    getDataList(params) {
      this.currentMethod
        .get(params)
        .then((res) => {
          if (res.status && res.data) {
            this.list = res.data.list
            this.total = res.data.total
          } else {
            this.list = []
            this.total = 0
          }
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },

    addMembers(userList) {
      this.userNumber++

      if (userList.length < 1) return false

      let addUserIdList = userList.map((item) => {
        return item.id
      })

      this.listLoading = true
      this.showMemberDialog = false

      if (this.multiPortal) {
        let obj = Object.assign(
          { id: this.portalId },
          { addUserIdList: addUserIdList }
        )

        Auth.getPortals(obj)
          .then((res) => {
            if (res.status) {
              this.saveMember(userList)
            }
          })
          .catch(() => {
            this.listLoading = false
          })
      } else {
        this.saveMember(userList)
      }
    },
    saveMember(userList) {
      let idList = userList.map((item) => {
        return item.id
      })
      const data = {
        roleId: this.data.id,
        userIdList: idList,
        userGroupIdList: idList,
        relationIdList: idList
      }

      this.currentMethod
        .save(data)
        .then((res) => {
          if (res.status) {
            this.$message({
              message: this.LANG.SAVE_SUCCESS,
              type: 'success'
            })
            this.fetchData()
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },

    handleDelete() {
      this.$confirm(this.LANG.DELETE_TIP, {
        title: this.LANG.TIPS,
        type: 'warning',
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      })
        .then(() => {
          const data = {
            roleId: this.data.id,
            userIdList: this.delList,
            userGroupIdList: this.delList
          }
          this.deleteMember(data)
        })
        .catch(() => {})
    },
    deleteMember(data) {
      this.currentMethod
        .delete(data)
        .then((res) => {
          if (res.status) {
            this.$message({
              message: this.LANG.DELETE_SUCCESS,
              type: 'success'
            })
            this.fetchData()
          }
        })
        .catch(() => {})
    }
  }
}
</script>

<style lang="scss" scoped>
.authorize {
  position: relative;
  height: calc(92vh - 225px);
}

::v-deep .fks-query-page {
  margin: 0 !important;
}

::v-deep .fks-dialog__body {
  padding: 0;
}
</style>
